package com.gxa.service.impl;

import com.gxa.dto.ResultData;
import com.gxa.mapper.PermissionMapper;
import com.gxa.mapper.RolePermissionMapper;
import com.gxa.pojo.Permission;
import com.gxa.pojo.RolePermission;
import com.gxa.pojo.RolePermissionExample;
import com.gxa.service.PermissionService;
import com.gxa.utils.Code;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: tyg
 * Date: 2020/07/20 10:12
 * Version: V1.0
 * Description:
 */
@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public ResultData listAllPermission() {
        ResultData<Object> resultData = new ResultData<>();
        List<Permission> permissions = permissionMapper.selectByExample(null);
        resultData.setData(permissions);
        resultData.setCode(Code.SUCCESS);
        return resultData;
    }

    @Override
    public ResultData insertPermission(Permission permission) {
        ResultData<Object> resultData = new ResultData<>();
        try {
            int i = permissionMapper.insertSelective(permission);
            if (i > 0){
                resultData.setCode(Code.SUCCESS);
            } else{
                resultData.setCode(Code.FALISE);
            }
        } catch (Exception e) {
            resultData.setCode(Code.FALISE);
            e.printStackTrace();
        }
        return resultData;
    }

    @Override
    public ResultData updatePermission(Permission permission) {
        ResultData<Object> resultData = new ResultData<>();
        try {
            int i = permissionMapper.updateByPrimaryKeySelective(permission);
            if (i > 0){
                resultData.setCode(Code.SUCCESS);
            } else{
                resultData.setCode(Code.FALISE);
            }
        } catch (Exception e) {
            resultData.setCode(Code.FALISE);
            e.printStackTrace();
        }
        return resultData;
    }

    @Override
    public ResultData removePermission(int permissionId) {
        ResultData<Object> resultData = new ResultData<>();
        try {
            // 删除权限表
            permissionMapper.deleteByPrimaryKey(permissionId);
            // 删除角色权限中间表
            RolePermissionExample example = new RolePermissionExample();
            example.createCriteria().andPermissionIdEqualTo(permissionId);
            int i = rolePermissionMapper.deleteByExample(example);
            resultData.setCode(Code.SUCCESS);
        } catch (Exception e) {
            resultData.setCode(Code.FALISE);
            e.printStackTrace();
        }
        return resultData;
    }
}
